package com.wiscamp.ninechapters.threeparties.mathpix;

import com.wiscamp.ninechapters.common.rest.ResourceHelper;
import com.wiscamp.ninechapters.common.rest.RestResponse;
import cube.ddd.adapter.BaseController;
import cube.ddd.aspect.HandleResourceException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.ws.rs.core.Context;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/ThreeParties")
@Tag(name = "第三方服务-数学公式识别")
public class MathpixController extends BaseController {

    private final MathpixService mathpixService;

    public MathpixController(MathpixService mathpixService) {
        this.mathpixService = mathpixService;
    }

    @PostMapping("OCR/Mathpix")
    @Operation(summary = "通过Base64编码的图片识别出latex公式")
    @HandleResourceException
    public RestResponse<OCRResponse> getImageLatex(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody MathpixRequestDto dto) {
        OCRResponse result;
        if (dto.getImageUrl() != null && !dto.getImageUrl().isEmpty()) {
            result = mathpixService.getImageLatex(dto.getImageUrl());
        } else {
            result = mathpixService.getLatexFromBase64Image(dto.getImageBase64());
        }
        return ResourceHelper.getOkResponse(request, response, result);
    }
}
